<?php

namespace app\api\controller;

use Firebase\JWT\ExpiredException;
use Firebase\JWT\Key;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;
use think\Exception;





class JwtService
{
    const key = 'wissun';
    const alg = 'HS256';
    const exp_time = 7200; //有效期


    public static function create_token($info = [])
    {
        $time = time();
        $payload = [
            'iss' => 'wissun',
            'iat' => $time,
            'exp' => $time + self::exp_time,
            'info' => $info
        ];
        return JWT::encode($payload, self::key, self::alg);
    }

    public static function check_token($payload){
        try {
            $payload = JWT::decode($payload, new Key(self::key, self::alg));
//            $ip = get_client_ip();
//            if ($ip != $payload->info->ip){
//                return ['code'=>2,'msg'=>'IP error'];
//            }else{
                return ['code'=>1,'data'=>(array)$payload->info];
//            }
        } catch (Exception $exception){
            return ['code'=>0,'msg'=>$exception];
        } catch (ExpiredException $exception){
            return ['code'=>2,'msg'=>'token expired'];
        } catch (SignatureInvalidException $exception){
            return ['code'=>0,'msg'=>'token error'];
        }
    }
}